/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bigo;

import bigo.data.MatrixMeta;
import bigo.multiplication.CalculationDriver;
import bigo.multiplication.PartitionDriver;
import bigo.multiplication.PartitionSchema;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 *
 * @author songliu
 */
public class MultiplicationDriver extends Configured implements Tool {

    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        int m = Integer.parseInt(args[3]), k = Integer.parseInt(args[4]),
                n = Integer.parseInt(args[5]);

        int bm = Integer.parseInt(args[6]), bk = Integer.parseInt(args[7]),
                bn = Integer.parseInt(args[8]);

        FileContext fs = FileContext.getFileContext(conf);
        fs.delete(new Path("output"), true);

        boolean isATransposed = args[0].endsWith("_T");
        boolean isBTransposed = args[1].endsWith("_T");
        boolean isCTransposed = args[2].endsWith("T");

        conf.setBoolean("trans.A", isATransposed);
        conf.setBoolean("trans.B", isBTransposed);
        conf.setBoolean("rowbased", !isCTransposed);

        new PartitionSchema(isATransposed ? bk : bm,
                isATransposed ? bm : bk,
                isBTransposed ? bn : bk,
                isBTransposed ? bk : bn).writeToConfiguration(conf);

        int res = ToolRunner.run(conf,
                new PartitionDriver(
                new MatrixMeta(args[0].replaceAll("_T", ""), isATransposed ? k : m,
                isATransposed ? m : k, isATransposed),
                new MatrixMeta(args[1].replaceAll("_T", ""), isBTransposed ? n : k,
                isBTransposed ? k : n, isBTransposed)),
                args);
        if (res != 0) {
            return res;
        }

        res = ToolRunner.run(conf,
                new CalculationDriver(new MatrixMeta(args[2], m, n)),
                args);
        return res;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Configuration(), new MultiplicationDriver(), args);
    }
}
